﻿using UnityEngine;
using System.Collections;
using System.IO;
using System;

//function：network protocol(proto-buffer) basic function
public static class Protocol
{

	public static byte[] StreamToBytes(Stream stream)
	{
		byte[] bytes = new byte[stream.Length];
		stream.Seek(0, SeekOrigin.Begin); 
		stream.Read(bytes, 0, (int)stream.Length);
		stream.Seek(0, SeekOrigin.Begin); 
		return bytes;
	}
	
	public static Stream BytesToStream(byte[] bytes)
	{
		return new MemoryStream(bytes);
	}

	/// Proto-buffer serialize.
    public static byte[] ProtoBufSerialize<T>(T protobuf)
	{
		MemoryStream stream = new MemoryStream();

		ProtoBuf.Serializer.Serialize(stream, protobuf);
		
		byte[] bytes = new byte[stream.Length];
		stream.Seek(0, SeekOrigin.Begin);
		stream.Read(bytes, 0, (int)stream.Length);
		return bytes;
	}

	// Proto-buffer de-serialize.
	public static T ProtoBufDeserialize<T>(byte[] bytes) where T:new()
	{
		MemoryStream stream = new MemoryStream(bytes);
		return ProtoBuf.Serializer.Deserialize<T>(stream);
	}

}
